import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { BlocklyComponent } from '../blockly/blockly.component';

@Component({
  selector: 'app-blockly-page',
  templateUrl: './blockly-page.component.html',
  styleUrls: ['./blockly-page.component.scss']
})
export class BlocklyPageComponent implements OnInit {
  // Variables for the modal
  showVariableModal: boolean = false;
  systemVariables: any[] = [
    {
      id: 1,
      name: '@Device1.Temperature',
      path: '@Device1.Temperature',
      type: 'number',
    },
    {
      id: 2,
      name: '@Device1.Humidity',
      path: '@Device1.Humidity',
      type: 'number',
    },
    { id: 3, name: '@Device1.Status', path: '@Device1.Status', type: 'string' },
    {
      id: 4,
      name: '@Device2.Temperature',
      path: '@Device2.Temperature',
      type: 'number',
    },
    {
      id: 5,
      name: '@Device2.Pressure',
      path: '@Device2.Pressure',
      type: 'number',
    },
    { id: 6, name: '@System.Time', path: '@System.Time', type: 'date' },
    { id: 7, name: '@System.Date', path: '@System.Date', type: 'date' },
    { id: 8, name: '@System.User', path: '@System.User', type: 'string' },
    // Add some additional variables specific to this page
    { id: 9, name: '@Page.Parameter1', path: '@Page.Parameter1', type: 'string' },
    { id: 10, name: '@Page.Parameter2', path: '@Page.Parameter2', type: 'number' },
  ];
  filteredSystemVariables: any[] = [];
  variableSearchTerm: string = '';
  selectedVariable: any = null;

  currentBlock: any = null;

  @ViewChild(BlocklyComponent) blocklyComponent!: BlocklyComponent;
  @ViewChild('fileInput') fileInput!: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  generateCode(): void {
    if (this.blocklyComponent) {
      const code = this.blocklyComponent.generateCode();
      const codeOutput = document.getElementById('blocklyCodeOutput');
      if (codeOutput) {
        codeOutput.textContent = code;
      }
    }
  }

  // 保存工作区到 localStorage
  saveWorkspace(): void {
    if (this.blocklyComponent) {
      this.blocklyComponent.saveWorkspace();
      alert('工作区已保存到本地存储');
    }
  }

  // 导出工作区为 XML 文件
  exportWorkspace(): void {
    if (this.blocklyComponent) {
      const xml = this.blocklyComponent.exportWorkspace();

      // 创建 Blob 对象
      const blob = new Blob([xml], { type: 'application/xml' });

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'blockly-workspace-page.xml';

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 0);
    }
  }

  // 打开文件选择对话框
  importWorkspace(): void {
    this.fileInput.nativeElement.click();
  }

  // 处理文件输入
  handleFileInput(event: Event): void {
    const fileInput = event.target as HTMLInputElement;
    const file = fileInput.files?.[0];

    if (file) {
      const reader = new FileReader();

      reader.onload = (e) => {
        const xmlText = e.target?.result as string;
        if (xmlText && this.blocklyComponent) {
          try {
            this.blocklyComponent.importWorkspace(xmlText);
            alert('工作区已成功导入');
          } catch (error) {
            console.error('导入工作区失败:', error);
            alert('导入工作区失败: ' + error);
          }
        }
      };

      reader.readAsText(file);

      // 清空文件输入
      fileInput.value = '';
    }
  }
  // Variable modal methods
  openVariableModal = (block?: any): void => {
    console.log('Opening variable modal');
    this.currentBlock = block || null;
    this.showVariableModal = true;
    this.filteredSystemVariables = [...this.systemVariables];
    this.variableSearchTerm = '';
    this.selectedVariable = null;
  };

  closeVariableModal() {
    this.showVariableModal = false;
  }

  filterVariables() {
    if (!this.variableSearchTerm) {
      this.filteredSystemVariables = [...this.systemVariables];
      return;
    }

    const searchTerm = this.variableSearchTerm.toLowerCase();
    this.filteredSystemVariables = this.systemVariables.filter((variable) =>
      variable.name.toLowerCase().includes(searchTerm)
    );
  }

  selectVariable(variable: any): void {
    this.selectedVariable = variable;

    // Add the selected variable to the workspace
    if (this.currentBlock) {
      // If a block was provided when opening the modal, use it
      // Logic to apply the selected variable to the block
    } else {
      // Otherwise create a new variable block
      this.blocklyComponent.importVariable(variable);
    }

    this.closeVariableModal();
  }

  importSelectedVariable(): void {
    if (!this.selectedVariable) {
      alert('请选中一个变量');
      return;
    }

    console.log('Importing variable:', this.selectedVariable);

    // 将选中的变量添加到工作区
    try {
      this.blocklyComponent.importVariable(this.selectedVariable);
      this.closeVariableModal();
      alert('变量已成功导入: ' + this.selectedVariable.name);
    } catch (error) {
      console.error('导入变量失败:', error);
      alert('导入变量失败: ' + error);
    }
  }
}
